import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { pinyin } from 'pinyin-pro'

export const useChatListStore = defineStore('chatlist', () => {
    const data = reactive([
        {
            id: '100001',
            username: '环境变量',
            type: 'friend',
            avartar: 'Cat.svg',
            message: '设置环境变量在这里..',
        },
        {
            id: '100003',
            username: 'taffy',
            type: 'friend',
            nickname: 'Ace Taffy',
            avartar:
                'https://img0.baidu.com/it/u=3239189170,4029423&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
            message: 'v灌注永÷塔菲喵~',
            time: '1-9',
            unreadNum: 3
        },
        {
            id: '100005',
            username: 'wolfsan',
            type: 'friend',
            nickname: 'Mr. Wolf',
            avartar: 'Wolf.svg',
            message: '',
            time: '1-9',
            unreadNum: 0
        }
    ])

    const query = ref('')
    const simplifiedQuery = computed(() => query.value.replace(/\s/g, '').toLowerCase())
    const filteredData = computed(() =>
        data.filter((item) => {
            if (!simplifiedQuery.value) return true
            const nickname = item.nickname.toLowerCase()
            const firstPinyin = pinyin(nickname, {
                pattern: 'first',
                toneType: 'none'
            }).replace(/\s/g, '')
            console.log(firstPinyin)
            if (firstPinyin.includes(simplifiedQuery.value)) {
                return true
            }
            return false
        })
    )

    const activeID = ref('000000')

    function deleteOne(id) {
        for (let index in data) {
            if (data[index].id == id) {
                data.splice(index, 1)
                break
            }
        }
    }

    function insertOne(item) {
        data.unshift(item)
    }

    function insertMany(items) {
        for (let i = items.length - 1; i >= 0; i--) {
            data.unshift(items[i])
        }
    }

    function findOneByID(id) {
        for (let item of data) {
            if (item.id == id) {
                return item
            }
        }
    }

    return {
        data,
        activeID,
        query,
        filteredData,
        deleteOne,
        insertOne,
        insertMany,
        findOneByID
    }
})
